package org.gnyxy.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.gnyxy.constant.DeleteConstant;
import org.gnyxy.constant.MessageConstant;
import org.gnyxy.context.BaseContext;
import org.gnyxy.dto.*;
import org.gnyxy.entity.*;
import org.gnyxy.exception.BaseException;
import org.gnyxy.exception.OrderBusinessException;
import org.gnyxy.exception.ShoppingCartBusinessException;
import org.gnyxy.mapper.*;
import org.gnyxy.result.PageResult;
import org.gnyxy.service.CartService;
import org.gnyxy.service.OrdersService;
import org.gnyxy.utils.WeChatPayUtil;
import org.gnyxy.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrdersServiceImpl implements OrdersService {

    //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
    public static final Integer UN_PAY = 1;
    public static final Integer WAIT_ORDER = 2;
    public static final Integer RECEIVED_ORDER = 3;
    public static final Integer ON_DELIVERY = 4;
    public static final Integer COMPLETED = 5;
    public static final Integer CANCELLED = 6;
    //支付状态 0未付款 1已付款 2退款
    public static final Integer PAY_STATUS_0 = 0;
    public static final Integer PAY_STATUS_1 = 1;
    public static final Integer PAY_STATUS_2 = 2;

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private CartService cartService;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private CartInfoMapper cartInfoMapper;
    @Autowired
    private MaterialMapper materialMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Override
    @Transactional
    public OrdersSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        // 校验传入值
        if (ordersSubmitDTO == null){
            throw new BaseException(MessageConstant.OBJECT_IS_NULL);
        }
        // Bean拷贝
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        // 获取当前线程用户id
        Long userId = BaseContext.getCurrentId();
        // 查询默认地址并校验和注入
        AddressVO addressVO = addressMapper.selectDefaultByUserId(userId);
        if (addressVO == null){
            throw new BaseException(MessageConstant.ADDRESS_IS_NULL);
        }
        // 查询购物车详情
        CartVOWithAmount cartVOWithAmount = cartService.getByUserId(userId);
        if (cartVOWithAmount == null) throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        orders.setUserId(userId)
                .setAddressId(addressVO.getId())
                .setConsignee(addressVO.getConsignee())
                .setStatus(UN_PAY)
                .setPayStatus(PAY_STATUS_0)
                .setOrderTime(LocalDateTime.now())
                .setNumber(String.valueOf(System.currentTimeMillis()))
                .setAddress(addressVO.getAddressDetail())
                .setAmount(cartVOWithAmount.getBigAmount())
                .setDeleted(DeleteConstant.IS_NOT_DELETED);

        // 插入并获取插入后生成的id
        ordersMapper.insert(orders);
        // 开始插入订单详情表
        List<OrderDetail> orderDetails = new ArrayList<>();

        List<CartVO> cartVOS = cartVOWithAmount.getCartVOS();
//        if (cartVOS.isEmpty()) throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);

        List<Long> cartIds = new ArrayList<>();
        for (CartVO cartVO : cartVOS) {
            OrderDetail orderDetail = new OrderDetail();
            Long dishId = cartVO.getDishId();
            orderDetail.setOrderId(orders.getId())
                    .setName(cartVO.getDishName() == null ?
                            cartVO.getMaterialName() :
                            cartVO.getDishName())
                    .setImage(cartVO.getImage())
                    .setDishId(dishId)
                    .setMaterialId(cartVO.getMaterialId())
                    .setNumber(cartVO.getNumber())
                    .setAmount(cartVO.getAmount())
                    .setDeleted(DeleteConstant.IS_NOT_DELETED);
//            // 确保添加进来的都是菜品而非食材
//            if (dishId != null)
            cartIds.add(cartVO.getId());
            orderDetails.add(orderDetail);
        }


        if (cartIds.isEmpty()) throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        // 查询购物车详情
        List<CartInfo> cartInfos = cartInfoMapper.getByCartIds(cartIds);

        if (!cartInfos.isEmpty()){
            // 作为菜品内容的集合
            List<DishContentMaterialVO> dishContentMaterialVOS = new ArrayList<>();
            List<Long> materialIds = new ArrayList<>();
            for (CartInfo cartInfo : cartInfos) {
                DishContentMaterialVO dishContentMaterialVO =
                        new DishContentMaterialVO()
                                .setDishId(cartInfo.getDishId())
                                .setMaterialId(cartInfo.getMaterialId())
                                .setMaterialNumber(cartInfo.getMaterialNumber());
                dishContentMaterialVOS.add(dishContentMaterialVO);
                materialIds.add(cartInfo.getMaterialId());
            }
            List<Material> materials = materialMapper.getByIds(materialIds);
            // 设置名字等信息
            for (DishContentMaterialVO dishContentMaterialVO : dishContentMaterialVOS) {
                for (Material material : materials) {
                    if (dishContentMaterialVO.getMaterialId().equals(material.getId())){
                        dishContentMaterialVO.setMaterialName(material.getName())
                                .setMaterialImage(material.getImage())
                                .setMaterialDefaultPrice(material.getDefaultPrice())
                                .setMaterialUnit(material.getUnit())
                                .setMaterialPrice(material.getPrice());
                    }
                }
            }

            for (OrderDetail orderDetail : orderDetails) {
                List<DishContentMaterialVO> dishContents = new ArrayList<>();
                Long dishId = orderDetail.getDishId();
                for (DishContentMaterialVO dishContentMaterialVO : dishContentMaterialVOS) {
                    if (dishId != null && dishId.equals(dishContentMaterialVO.getDishId())){
                        dishContents.add(dishContentMaterialVO);
                    }
                }

                if (dishId != null){
                    //防止转义
                    String dishContentsJSON = JSON.toJSONString(dishContents,SerializerFeature.WriteSlashAsSpecial);
                    log.info("{}", dishContentsJSON);
                    orderDetail.setDishContent(dishContentsJSON);
                }

            }
        }


        if (!orderDetails.isEmpty()){
            orderDetailMapper.insert(orderDetails);
        }
        // 删除购物车
        cartService.deleteCartsByIds(cartIds);

        return new OrdersSubmitVO().setId(orders.getId())
                .setNumber(orders.getNumber())
                .setOrderTime(orders.getOrderTime());
    }

    /**
     * 订单支付
     * @param ordersPaymentDTO
     * @return
     */
    @Override
    @Transactional
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) {
        // 获取当前用户
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);
        Orders orders = ordersMapper.getByOrderNumber(ordersPaymentDTO.getOrderNumber());
        JSONObject pay = null;
        //调用微信支付接口，生成预支付交易单
        try{
             pay = weChatPayUtil.pay(
                    ordersPaymentDTO.getOrderNumber(), //商户订单号
                    orders.getAmount(),// 订单金额
                    "订单" + ordersPaymentDTO.getOrderNumber(),
                    user.getOpenid()
            );
             log.info("支付信息:{}",pay);
        } catch (Exception e){
            log.info("抛出异常为{}",e);
        }

        if (pay != null && pay.getString("code") != null && pay.getString("code").equals("ORDERPAID")){
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO paymentVO = pay.toJavaObject(OrderPaymentVO.class);
        paymentVO.setPackageStr(pay.getString("package"));
        return paymentVO;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = new Orders()
                .setId(ordersDB.getId())
                .setStatus(WAIT_ORDER)
                .setPayStatus(PAY_STATUS_1)
                .setCheckoutTime(LocalDateTime.now());
//                .id(ordersDB.getId())
//                .status(Orders.TO_BE_CONFIRMED)
//                .payStatus(Orders.PAID)
//                .checkoutTime(LocalDateTime.now());

        ordersMapper.update(orders);
    }

    @Override
    public PageResult PageQuery(Integer pageNum, Integer pageSize, Integer status) {
        // 分页校验
        if (pageNum == null) pageNum = 1;
        if (pageSize == null) pageSize = 10;
        // 设置分页
        PageHelper.startPage(pageNum, pageSize);

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        // 分页条件查询
        Page<Orders> page = ordersMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList<>();

        // 查询出订单明细，并封装入OrderVO进行响应
        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                Long orderId = orders.getId();// 订单id

                // 查询订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);
                // 创建vo
                List<OrderDetailVO> orderDetailVOS = new ArrayList<>();
                for (OrderDetail orderDetail : orderDetails) {
                    OrderDetailVO orderDetailVO = new OrderDetailVO();
                    BeanUtils.copyProperties(orderDetail,orderDetailVO);
                    orderDetailVO.setDishContent(parseDishContent(orderDetail.getDishContent()));
                    orderDetailVOS.add(orderDetailVO);
                }
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetailVOS);

                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), list);
    }

    @Override
    public OrderVO details(Long id) {
        // 根据id查询订单
        Orders orders = ordersMapper.getById(id);

        // 查询该订单对应的菜品/菜品材料明细
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orders.getId());
        List<OrderDetailVO> orderDetailVOS = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetails) {
            OrderDetailVO orderDetailVO = new OrderDetailVO();
            BeanUtils.copyProperties(orderDetail,orderDetailVO);
            orderDetailVO.setDishContent(parseDishContent(orderDetail.getDishContent()));
            orderDetailVOS.add(orderDetailVO);
        }
        // 将该订单及其详情封装到OrderVO并返回
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailVOS);

        return orderVO;
    }

    /**
     * 用户取消订单
     *
     * @param id
     */
    public void userCancelById(Long id) throws Exception {
        // 根据id查询订单
        Orders ordersDB = ordersMapper.getById(id);

        // 校验订单是否存在
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (ordersDB.getStatus() > WAIT_ORDER) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());

        // 订单处于待接单状态下取消，需要进行退款
        if (ordersDB.getStatus().equals(WAIT_ORDER)) {
            //调用微信支付退款接口
            weChatPayUtil.refund(
                    ordersDB.getNumber(), //商户订单号
                    ordersDB.getNumber(), //商户退款单号
                    ordersDB.getAmount(),//退款金额，单位 元
                    ordersDB.getAmount());//原订单金额

            //支付状态修改为 退款
            orders.setPayStatus(PAY_STATUS_2);
        }

        // 更新订单状态、取消原因、取消时间
        orders.setStatus(CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        ordersMapper.update(orders);
    }

    /**
     * 订单搜索
     *
     * @param ordersPageQueryDTO
     * @return
     */
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        Page<Orders> page = ordersMapper.pageQuery(ordersPageQueryDTO);

        // 部分订单状态，需要额外返回订单菜品信息，将Orders转化为OrderVO
        List<OrderVO> orderVOList = getOrderVOList(page);

        return new PageResult(page.getTotal(), orderVOList);
    }

    /**
     * 各个状态的订单数量统计
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        // 根据状态，分别查询出待接单、待派送、派送中的订单数量
        Integer toBeConfirmed = ordersMapper.countStatus(WAIT_ORDER);
        Integer confirmed = ordersMapper.countStatus(RECEIVED_ORDER);
        Integer deliveryInProgress = ordersMapper.countStatus(ON_DELIVERY);

        // 将查询出的数据封装到orderStatisticsVO中响应
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = new Orders()
                .setId(ordersConfirmDTO.getId())
                        .setStatus(RECEIVED_ORDER);
//        Orders.builder()
//                .id(ordersConfirmDTO.getId())
//                .status(Orders.CONFIRMED)
//                .build();

        ordersMapper.update(orders);
    }

    /**
     * 拒单
     *
     * @param ordersRejectionDTO
     */
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        // 根据id查询订单
        Orders ordersDB = ordersMapper.getById(ordersRejectionDTO.getId());

        // 订单只有存在且状态为2（待接单）才可以拒单
        if (ordersDB == null || !ordersDB.getStatus().equals(WAIT_ORDER)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus.equals(PAY_STATUS_1)) {
            //用户已支付，需要退款
            String refund = weChatPayUtil.refund(
                    ordersDB.getNumber(),
                    ordersDB.getNumber(),
                    ordersDB.getAmount(),
                    ordersDB.getAmount());
            log.info("申请退款：{}", refund);
        }

        // 拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());

        ordersMapper.update(orders);
    }

    /**
     * 取消订单
     *
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) throws Exception {
        // 根据id查询订单
        Orders ordersDB = ordersMapper.getById(ordersCancelDTO.getId());

        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus.equals(PAY_STATUS_1)) {
            //用户已支付，需要退款
            String refund = weChatPayUtil.refund(
                    ordersDB.getNumber(),
                    ordersDB.getNumber(),
                    ordersDB.getAmount(),
                    ordersDB.getAmount());
            log.info("申请退款：{}", refund);
        }

        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersCancelDTO.getId());
        orders.setStatus(CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        ordersMapper.update(orders);
    }

    /**
     * 派送订单
     *
     * @param id
     */
    public void delivery(Long id) {
        // 根据id查询订单
        Orders ordersDB = ordersMapper.getById(id);

        // 校验订单是否存在，并且状态为3
        if (ordersDB == null || !ordersDB.getStatus().equals(RECEIVED_ORDER)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 更新订单状态,状态转为派送中
        orders.setStatus(ON_DELIVERY);

        ordersMapper.update(orders);
    }

    /**
     * 完成订单
     *
     * @param id
     */
    public void complete(Long id) {
        // 根据id查询订单
        Orders ordersDB = ordersMapper.getById(id);

        // 校验订单是否存在，并且状态为4
        if (ordersDB == null || !ordersDB.getStatus().equals(ON_DELIVERY)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 更新订单状态,状态转为完成
        orders.setStatus(COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());

        ordersMapper.update(orders);
    }

    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        // 需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList = new ArrayList<>();

        List<Orders> ordersList = page.getResult();
        if (!CollectionUtils.isEmpty(ordersList)) {
            for (Orders orders : ordersList) {
                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orders.getId());
                List<OrderDetailVO> orderDetailVOS = new ArrayList<>();
                for (OrderDetail orderDetail : orderDetails) {
                    OrderDetailVO orderDetailVO = new OrderDetailVO();
                    BeanUtils.copyProperties(orderDetail,orderDetailVO);
                    orderDetailVO.setDishContent(parseDishContent(orderDetail.getDishContent()));
                    orderDetailVOS.add(orderDetailVO);
                }
                orderVO.setOrderDetailList(orderDetailVOS);
//                String orderDishes = getOrderDishesStr(orders);
                List<String> orderDishes = new ArrayList<>();
                for (OrderDetailVO orderDetail : orderDetailVOS) {
                    orderDishes.add(orderDetail.getName() + "*" + orderDetail.getNumber()+";");
                }
                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setDishContent(String.join("",orderDishes));
                orderVOList.add(orderVO);
            }
        }
        return orderVOList;
    }

    private List<DishContentMaterialVO> parseDishContent(String dishContent) {
        List<DishContentMaterialVO> dishContentList = JSON.parseArray(dishContent, DishContentMaterialVO.class);
        return dishContentList;
    }

}
